import cv2
import numpy as np
import csv

# 定义全局变量
drawing = False  # 是否正在绘制矩形
ix, iy = -1, -1  # 起始点坐标


def normalize_matrix(np_matrix):
    """
    对NumPy矩阵进行最小-最大归一化，并转换为0-255范围的图像。
    """
    # 找到矩阵中的最小值和最大值
    np_matrix_min = np.min(np_matrix)
    np_matrix_max = np.max(np_matrix)

    # 对矩阵进行最小-最大归一化，将其值缩放到0-1范围
    normalized_matrix = (np_matrix - np_matrix_min) / (np_matrix_max - np_matrix_min)

    # 将归一化后的矩阵缩放到0-255范围，并转换为uint8类型
    scaled_matrix = (normalized_matrix * 255).astype(np.uint8)

    return scaled_matrix


# 读取CSV文件并转换为NumPy数组
def read_csv_to_matrix(csv_file):
    with open(csv_file, 'r') as file:
        reader = csv.reader(file)
        matrix = [list(map(float, row)) for row in reader]
    return np.array(matrix)


# 鼠标事件回调函数
def draw_rectangle(event, x, y, flags, param):
    global ix, iy, drawing

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.rectangle(img, (ix, iy), (x, y), (255, 0, 0), 2)

        # 计算框内区域的灰度平均值
        roi = npMatrix[iy:y, ix:x]
        mean_value = np.mean(roi)

        # 输出信息
        print(f"灰度平均值: {round(mean_value, 3)}")
        print(f"框内区域的行列信息: 行  列  {iy}, {y}, {ix}, {x}")


if __name__ == "__main__":
    csv_file = r"E:\infraVideos\20240524\1\0.070000hz.csv"
    matrix = read_csv_to_matrix(csv_file)
    npMatrix = np.array(matrix)

    # 将NumPy数组转换为图像（假设数组值在0到1之间）
    img = normalize_matrix(npMatrix)
    # 创建窗口并将回调函数绑定到窗口
    cv2.namedWindow('image')
    cv2.setMouseCallback('image', draw_rectangle)

    while True:
        cv2.imshow('image', img)

        # 通过按键 'ESC' 退出循环
        if cv2.waitKey(1) & 0xFF == 27:
            break

    cv2.destroyAllWindows()
